package com.example.springframeworklearning.config;

import com.example.springframeworklearning.propertyeditor.registrar.MyPropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.example.springframeworklearning.domain.Order;
import com.example.springframeworklearning.domain.OrderItem;
import com.example.springframeworklearning.propertyeditor.LocalDateTimePropertyEditor;
import com.example.springframeworklearning.propertyeditor.OrderItemListPropertyEditor;

import java.beans.PropertyEditor;
import java.util.HashMap;
import java.util.Map;

/**
 * 在 spring ioc 容器下，只需要把此配置类注入到 ioc 容器中
 * 对应的 BeanWrapper 就会自动的使用这里定义的 PropertyEditor 来处理 bean 中的属性
 * @author luo
 * @since 2022/9/19 15:19
 */
@Configuration
public class CustomEditorConfig {

    @Bean
    public CustomEditorConfigurer customEditorConfigurer() {
        CustomEditorConfigurer result = new CustomEditorConfigurer();


//      以 BeanFactoryPostProcessor 的形式 往 ioc 中注册 propertyEditor
        Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<>();
        customEditors.put(OrderItem.class, OrderItemListPropertyEditor.class);
        customEditors.put(Order.class, LocalDateTimePropertyEditor.class);
        result.setCustomEditors(customEditors);

        /**
         * 通过这个方法将 PropertyEditorRegistrar 添加到  CustomEditorConfigurer
         * 使得 PropertyEditorRegistrar 可以被 DataBinder 和 spring mvc controller 轻易的共享
         * 此外，为了避免 customEditors 同步
         * 每次 bean 被创建的时候，PropertyEditorRegistrar 都倾向于创建一个全新的 PropertyEditor
         */
        result.setPropertyEditorRegistrars(new PropertyEditorRegistrar[]{
                getMyPropertyEditorRegistrar()
        });


        return result;
    }

    @Bean
    public PropertyEditorRegistrar getMyPropertyEditorRegistrar() {
        return new MyPropertyEditorRegistrar();
    }
}
